<!--  -->
<template>
  <div class="app-container">
    <!-- header -->
    <el-card>
      <div slot="header" class="header">
        <span>模版管理</span>
        <el-button type="success" icon="el-icon-plus" size="small" @click="onClickAddTemplate">添加模版</el-button>
      </div>

      <div style="marginTop:20px" class="filter-container">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="模版名称">
            <el-input v-model="searchFormData.name" clearable></el-input>
          </el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onClickSearch">查询</el-button>
        </el-form>
      </div>
    </el-card>
    <!-- body -->
    <el-card style="marginTop:20px">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="#" min-width="15%" />
        <el-table-column prop="name" label="模板名称" min-width="20%" />
        <el-table-column prop="specDTOs" label="规格" min-width="35%" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="margin-right:10px" v-for="(spec,i) in scope.row.specDTOs" :key="i">
              <el-tag>{{spec.specificationName}}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="extendsProperties" label="扩展属性" min-width="35%" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="margin-right:10px" v-for="(prop,i) in scope.row.extendsProperties" :key="i">
              <el-tag type='info'>{{prop}}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="操作" min-width="15%">
          <template slot-scope="scope">
            <el-button @click="onClickEdit(scope.row)" type="text">编辑</el-button>
            <el-button class="red" @click="onClickDelete(scope.row)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="prev, pager, next" @current-change="currentChange" :page-count="Math.ceil(this.pageInfo.total / this.pageInfo.pageSize)"></el-pagination>
      </div>
    </el-card>
    <!-- dialog -->
    <el-dialog :visible.sync="dialogFormVisible" :destroy-on-close="true" width="50%" :title="editFormData.isEdit?'编辑模版':'添加模版'" :before-close="onCloseDialog">
      <el-form ref="editForm" :rules="editFormRules" :model="editFormData">
        <el-form-item label="模版名称" :label-width="formLabelWidth" prop="name" required>
          <el-input v-model="editFormData.name" placeholder="请输入模版名称" style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="规格" :label-width="formLabelWidth" prop="specIds" required>
          <el-select v-model="editFormData.specIds" filterable multiple collapse-tags placeholder="请选择规格" style="width: 100%;">
            <el-option v-for="item in specsOptions" :key="item.id" :label="item.specName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="扩展属性" :label-width="formLabelWidth">
          <el-tag :key="tag" v-for="tag in editFormData.extendsProperties" closable :disable-transitions="false" @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else type="success" class="button-new-tag" size="small" icon="el-icon-plus" @click="showInput">扩展属性</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClickResetForm">取 消</el-button>
        <el-button type="primary" @click="onClickSaveTemplate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: '80px',
      tableData: [],
      pageInfo: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 展示数量
        total: 1, // 总记录数
      },
      editFormData: {
        isEdit: false,
        name: '',
        specIds: [],
        extendsProperties: [],
      },
      editFormRules: {
        name: [{ required: true, message: '请输入模版名称', trigger: 'blur' }],
        specIds: [
          { required: true, message: '请选择模版规格', trigger: 'blur' },
        ],
      },
      specsOptions: [],

      searchFormData: {
        name: '',
      },

      inputVisible: false,
      inputValue: '',
    };
  },
  created() {},
  mounted() {
    this.getTemplate();
  },
  computed: {},
  methods: {
    /**
     * 取消重置form
     */
    onClickResetForm() {
      this.dialogFormVisible = false;
      this.$refs['editForm'].resetFields();
    },
    /**
     * 保存
     */
    onClickSaveTemplate() {
      this.$refs['editForm'].validate((valid) => {
        if (!valid) return;

        if (this.editFormData.isEdit) {
          this.updateTemplate();
        } else {
          this.addTemplate();
        }
      });
    },
    /**
     * 添加/编辑模版
     */
    onClickAddTemplate() {
      this.editFormData = { ...this.editFormData, ...{ isEdit: false } };
      this.showEditDialog();
    },
    /**
     * 编辑
     */
    onClickEdit(row) {
      const specIds = row.specDTOs.map((e) => {
        return e.specificationId;
      });
      this.editFormData = {
        ...this.editFormData,
        ...row,
        ...{ isEdit: true },
        ...{ specIds: specIds },
        ...{ extendsProperties: row.extendsProperties || [] },
      };
      this.showEditDialog();
    },
    /**
     * 删除
     */
    async onClickDelete({ id }) {
      const confirm = await this.$confirm(
        `此操作将永久删除该模版, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {});

      confirm && this.deleteTemplate(id);
    },

    /**
     * 当前页变更
     */
    currentChange(val) {
      this.pageInfo.pageNum = val;
      this.getTemplate();
    },

    /**
     * 对话框
     */
    showEditDialog() {
      this.dialogFormVisible = true;
      this.getSpecs();
    },

    /**
     * 关闭弹窗
     */
    onCloseDialog(done) {
      this.editFormData = { isEdit: false, name: '', specIds: [] };
      done();
    },

    /**
     * 搜索
     */
    onClickSearch() {
      this.pageInfo.pagesNo = 1;
      this.pageInfo.pageNum = 1;
      this.getTemplate();
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleClose(tag) {
      this.editFormData.extendsProperties.splice(
        this.editFormData.extendsProperties.indexOf(tag),
        1
      );
    },

    handleInputConfirm() {
      if (this.inputValue) {
        this.editFormData.extendsProperties.push(this.inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    async getTemplate() {
      const params = {
        name: this.searchFormData.name,
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize,
        needTotalCount: true,
      };
      const response = await this.$api.getTypeTemplate(params);
      this.tableData = response.data;
      this.pageInfo.total = response.total;
    },
    async addTemplate() {
      const { name, specIds, extendsProperties } = this.editFormData;
      const response = await this.$api.addTypeTemplate({
        specIds,
        name,
        extendsProperties,
      });
      if (response.success) {
        this.$message.success('添加成功');
        this.dialogFormVisible = false;
        this.getTemplate();
      }
    },
    async updateTemplate() {
      const { id, name, specIds, extendsProperties } = this.editFormData;
      const response = await this.$api.updateTypeTemplate({
        id,
        name,
        specIds,
        extendsProperties,
      });
      if (response.success) {
        this.$message.success('编辑成功');
        this.dialogFormVisible = false;
        this.getTemplate();
      }
    },
    async deleteTemplate(id) {
      const response = await this.$api.deleteTypeTemplate({ id });
      if (response.success) {
        this.$message.success('删除成功');
        this.getTemplate();
      }
    },
    async getSpecs() {
      const response = await this.$api.getSpecificationList();
      this.specsOptions = response.data.map((e) => {
        return {
          id: e.id,
          specName: e.specName,
        };
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    height: 32px;
    line-height: 32px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    vertical-align: bottom;
  }
}
</style>
